import * as Sass from 'sass' // 只引入 typings
import { config } from './config'
import { requireLocalPkg } from './requirePackage'

type SassType = typeof Sass

/**
 * 尝试加载本地 node-sass/sass
 */
function autoRequireSass(file: string): SassType {
  try {
    return requireLocalPkg<SassType>(file, 'sass')
  } catch (error) {
    return requireLocalPkg<SassType>(file, 'node-sass')
  }
}

/**
 * 渲染scss
 * @param op sass 配置
 */
export default function(file: string, content: string, op?: Sass.Options): Promise<string> {
  // const content = readFileSync(file).toString();

  const options: Sass.Options = {
    ...config.sass,
    ...op,
    file,
    data: content,
    sourceMap: false,
    sourceMapContents: false,
  }

  return new Promise((resolve, reject) => {
    try {
      autoRequireSass(file)
        .render(options, (error, result) => {
          if (error) {
            console.error(error);
            resolve(content);
          } else {
            resolve(result.css.toString());
          }
        });
    } catch (error) {
      console.error(error)
      resolve(content)
    }
  })
}
